import json

import pandas as pd
import requests
from retry import retry


def todayopportunity():
    """
    东方财富今日主题事件
    """
    result = pd.DataFrame()
    content = requests.get('http://quote.eastmoney.com/zhuti/api/todayopportunity')
    data = json.loads(content.text)
    theme_list = list()
    for content in data['result']:
        for con in content['Data']:
            con_arr = con.split('|')
            theme_list.append(con_arr[1])

    code_list = list()
    for code in theme_list:
        theme_content = requests.get('http://quote.eastmoney.com/zhuti/api/themerelatestocks?CategoryCode=' + code +
                                     '&startIndex=0&pageSize=10000')
        data = json.loads(theme_content.text)
        for content in data['result']:
            for con in content['Data']:
                con_arr = con.split('|')
                if con_arr[1].startswith('688') | len(con_arr[1]) != 6:
                    continue
                code_list.append(con_arr[1])

    result.insert(loc=0, column='代码', value=code_list)
    return result


def eastmoney_recent_hot_theme():
    """
    东方财富近期主题事件
    :return:
    """
    content = requests.get('https://quote.eastmoney.com/zhuti/api/recenthot')
    data = json.loads(content.text)
    theme_list = list()
    for content in data['result']:
        for con in content['Data']:
            con_arr = con.split('|')
            if con_arr[2] == '0':
                theme_list.append(con_arr[0])
            elif con_arr[2] == '1':
                sub_content = requests.get(
                    'https://quote.eastmoney.com/zhuti/api/topthemechildren?CategoryCode=' + con_arr[0])
                data = json.loads(sub_content.text)
                for theme in data['result']:
                    for theme_con in theme['Data']:
                        con_arr = theme_con.split('|')
                        theme_list.append(con_arr[0])

    code_list = list()
    for code in theme_list:
        theme_content = requests.get('https://quote.eastmoney.com/zhuti/api/themerelatestocks?CategoryCode=' + code +
                                     '&startIndex=0&pageSize=10000')
        data = json.loads(theme_content.text)
        for content in data['result']:
            for con in content['Data']:
                con_arr = con.split('|')
                if con_arr[1].startswith('688') | len(con_arr[1]) != 6:
                    continue
                code_list.append(con_arr[1])

    hot = pd.DataFrame()
    hot.insert(loc=0, column='代码', value=code_list)
    return hot


@retry(tries=10, delay=10, backoff=1)
def theme_stocks():
    """
    题材面整合
    """
    today_stocks = todayopportunity()
    recent_stocks = eastmoney_recent_hot_theme()
    theme_stocks_df = pd.merge(today_stocks, recent_stocks, on=['代码'], how='outer').drop_duplicates('代码')
    return theme_stocks_df['代码']
